package cn.wjdiankong.levideo.list.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import cn.wjdiankong.levideo.fragment.BaseFragment;

public class LevideoFragmentAdapter extends FragmentPagerAdapter {
	
    private List<BaseFragment> fragmentList = new ArrayList<BaseFragment>();
    private List<String> titleList = new ArrayList<String>();//用于记录Fragment的标题
    private Map<String, Integer> IdsMap = new HashMap<String, Integer>();
    private List<String> preIds = new ArrayList<String>();
    
    public LevideoFragmentAdapter(FragmentManager fm) {
		super(fm);
	}
    
    public void setFragmentList(List<BaseFragment> list){
    	fragmentList.clear();
    	fragmentList.addAll(list);
    }
    
    public void setTitleList(List<String> list){
    	titleList.clear();
    	titleList.addAll(list);
    	for(int i=0; i<titleList.size(); i++){
    		IdsMap.put(titleList.get(i), i);
    	}
    	preIds.clear();
        int size = getCount();
        for(int i=0; i<size; i++){
            preIds.add(getPageTitle(i).toString());
        }
    }
    
    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentList.get(position).getTitle();
    }

    @Override
    public long getItemId(int position) {
        return IdsMap.get(getPageTitle(position));
    }

    @Override
    public int getItemPosition(Object object) {
        BaseFragment fragment= (BaseFragment) object;
        String title = fragment.getTitle();
        int preId = preIds.indexOf(title);//获取当前Fragment的之前位置
        int newId = -1;
        int size = getCount();
        for(int i=0; i<size; i++){
            if(getPageTitle(i).equals(title)){
                newId = i;//计算到新的位置
                break;
            }
        }
        
        //如果位置没有发生变化
        if(newId != -1 && newId == preId){
            return POSITION_UNCHANGED;
        }
        
        //位置发生变化，就返回新的位置
        if(newId != -1){
            return newId;
        }
        //当前页不存在
        return POSITION_NONE;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }
}
